﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace StableDiffusionTools.Framework
{
    public class ThrottleProgress<T> : Progress<T>
    {
        private DateTime lastUpdate = DateTime.MinValue;

        public T LastProgress;
        public TimeSpan UpdatePeriod { get; protected set; }
        public ThrottleProgress(TimeSpan updatePeriod) : base()
        {
            UpdatePeriod = updatePeriod;
        }

        ///// <summary>Reports a progress change.</summary>
        ///// <param name="value">The value of the updated progress.</param>
        //protected virtual void OnReport(T value)
        //{
        //    // If there's no handler, don't bother going through the sync context.
        //    // Inside the callback, we'll need to check again, in case 
        //    // an event handler is removed between now and then.
        //    Action<T> handler = m_handler;
        //    EventHandler<T> changedEvent = ProgressChanged;
        //    if (handler != null || changedEvent != null)
        //    {
        //        // Post the processing to the sync context.
        //        // (If T is a value type, it will get boxed here.)
        //        m_synchronizationContext.Post(m_invokeHandlers, value);
        //    }
        //}
        protected override void OnReport(T value)
        {
            DateTime now = DateTime.UtcNow;
            if(now.Subtract(lastUpdate) >= UpdatePeriod)
            {
                lastUpdate = now;
                base.OnReport(value);
            }
        }
    }
}
